//
//  ViewController.swift
//  TableViewCellMovedDemo
//
//  Created by zxy on 2021/1/13.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    
    let tableView = UITableView()
    let array: NSMutableArray = [1,2,3,4,5,6,7,8,9,10]
    private var moveCellImg: UIView?
    private var originIndex: Int = -1   //初始移动下标

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        tableView.frame = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        
        //手势
        let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(drapCell))
        longPressGes.minimumPressDuration = 0.5
        tableView.addGestureRecognizer(longPressGes)
    }
    
    //MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        if cell == nil {
            cell = UITableViewCell(style: .value1, reuseIdentifier: "cell")
        }
        cell?.textLabel?.text = "num:\(array[indexPath.row])"
        return cell!
    }
}

///处理手势
extension ViewController {
    @objc func drapCell(longPressGes: UILongPressGestureRecognizer) {
        switch longPressGes.state {
        case .began:
            let point = longPressGes.location(in: tableView)
            if let indexPath = tableView.indexPathForRow(at: point) {
                if indexPath.row != 0 {
                    originIndex = indexPath.row
                    if let cell = tableView.cellForRow(at: indexPath) {
                        moveCellImg = cell.snapshotView(afterScreenUpdates: false)
                        view.addSubview(moveCellImg!)
                        setMoveImgVPoint(longPressGes: longPressGes)
                        //将要拖动的原cell隐藏
                        cell.isHidden = true
                    }
                }
            }
        case .changed:
            let point = longPressGes.location(in: tableView)
            if let indexPath = tableView.indexPathForRow(at: point) {
                if indexPath.row != originIndex && originIndex != -1 {
                    let sourceIndex = IndexPath(row: originIndex, section: 0)
                    tableView.moveRow(at: sourceIndex, to: indexPath)
                    array.exchangeObject(at: originIndex, withObjectAt: indexPath.row)
                    originIndex = indexPath.row
                }
            }
            setMoveImgVPoint(longPressGes: longPressGes)
        case.ended:
            let point = longPressGes.location(in: tableView)
            if let indexPath = tableView.indexPathForRow(at: point) {
                if indexPath.row == originIndex || originIndex == -1 {
                    resetMoveTableViewCellAnimation()
                    return
                }
                array.exchangeObject(at: originIndex, withObjectAt: indexPath.row)
            }
            resetMoveTableViewCellAnimation()
        default:
            resetMoveTableViewCellAnimation()
            break
        }
    }
    
    //cell跟随手指位置
    func setMoveImgVPoint(longPressGes: UILongPressGestureRecognizer) {
        let newPoin = longPressGes.location(in: view)
        moveCellImg?.x = newPoin.x - moveCellImg!.width / 2
        moveCellImg?.y = newPoin.y - moveCellImg!.height / 2
    }
    
    //结束动画
    func resetMoveTableViewCellAnimation() {
        moveCellImg?.removeFromSuperview()
        moveCellImg = nil
        tableView.reloadData()
    }
}
